package cn.fintecher.pangolin.service.manage.service;

import cn.fintecher.pangolin.common.enums.BaseStatus;
import cn.fintecher.pangolin.common.exception.BadRequestException;
import cn.fintecher.pangolin.entity.mysql.QUserDevice;
import cn.fintecher.pangolin.entity.mysql.UserDevice;
import cn.fintecher.pangolin.service.manage.repository.UserDeviceRepository;
import cn.fintecher.pangolin.service.manage.request.ModifyStatusRequest;
import cn.fintecher.pangolin.service.manage.response.UserDeviceResponse;
import org.apache.commons.collections4.IterableUtils;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 15:25 2019/8/15
 */

@Service("userDeviceService")
@Transactional(rollbackFor = Exception.class)
public class UserDeviceService {
    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private UserDeviceRepository userDeviceRepository;

    /**
     * 设备锁查询
     */
    public List<UserDeviceResponse> findAllUserDevice(String userId) {
        Iterable<UserDevice> iterable = userDeviceRepository.findAll(QUserDevice.userDevice.userId.eq(userId));
        Type listType = new TypeToken<List<UserDeviceResponse>>() {
        }.getType();
        return modelMapper.map(IterableUtils.toList(iterable), listType);
    }

    /**
     * 一键启/禁用设备锁
     */
    public void batchDeviceManage(BaseStatus status) {
        Iterable<UserDevice> iterable = userDeviceRepository.findAll();
        iterable.forEach(e -> e.setStatus(status));
        userDeviceRepository.saveAll(iterable);
    }

    /**
     * 启用/禁用设备
     */
    public void modifyStatus(ModifyStatusRequest request) {
        UserDevice userDevice = userDeviceRepository.findById(request.getId()).orElseThrow(() -> new BadRequestException(null, "userDevice", "userdevice.is.null"));
        userDevice.setStatus(request.getStatus());
        userDeviceRepository.save(userDevice);
    }

    /**
     * 重置设备
     */
    public void deleteUserDevice(String userDeviceId) {
        userDeviceRepository.deleteById(userDeviceId);
    }
}
